//
//  RefreshView.swift
//  WBDemo
//
//  Created by Meng on 17/2/16.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit
import SnapKit

class RefreshView: UIView {

    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var arrowImageView: UIImageView!

    @IBOutlet weak var loadingImageView: UIImageView!
    
    class func refreshView() -> RefreshView {
        return Bundle.main.loadNibNamed("RefreshView", owner: nil, options: nil)?.last as! RefreshView
    }
    // MARK: - 外部控制方法
    /// 旋转箭头
    func rotationArrow(flag: Bool)
    {
        var angle: CGFloat = flag ? -0.01 : 0.01
        angle += CGFloat(M_PI)
        /*
         transform旋转动画默认是按照顺时针旋转的
         但是旋转时还有一个原则, 就近原则
         */
        UIView.animate(withDuration: 0.5) { 
            self.arrowImageView.transform = self.arrowImageView.transform.rotated(by: angle)
        }
    }
    
    /// 显示加载视图
    func startLoadingView()
    {
        // 0.隐藏提示视图
        tipView.isHidden = true
        
        if let _ = loadingImageView.layer.animation(forKey: "lnj")
        {
            // 如果已经添加过动画, 就直接返回
            return
        }
        // 1.创建动画
        let anim =  CABasicAnimation(keyPath: "transform.rotation")
        
        // 2.设置动画属性
        anim.toValue = 2 * M_PI
        anim.duration = 1.0
        anim.repeatCount = MAXFLOAT
        
        // 3.将动画添加到图层上
        loadingImageView.layer.add(anim, forKey: "lnj")
    }
    
    /// 隐藏加载视图
    func stopLoadingView()
    {
        // 0.显示提示视图
        tipView.isHidden = false
        
        // 1.移除动画
        loadingImageView.layer.removeAllAnimations()
    }
}


class CustomRefreshControl: UIRefreshControl {
    
    override init() {
        super.init()
        addSubview(refreshView)
        refreshView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 150, height: 50))
            make.center.equalTo(self)
        }
        addObserver(self, forKeyPath: "frame", options: .new, context: nil)
    }
    
    var rotationFlag = false
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if frame.origin.y == 0 || frame.origin.y == -64 {
            return
        }
        // 判断是否触发下拉刷新事件
        if isRefreshing
        {
            // 隐藏提示视图, 显示加载视图, 并且让菊花转动
            refreshView.startLoadingView()
            return
        }
        if frame.origin.y < -50 && !rotationFlag {
            rotationFlag = true
            refreshView.rotationArrow(flag: true)
        } else if frame.origin.y > -50 && rotationFlag {
            rotationFlag = false
            refreshView.rotationArrow(flag: false)
        }
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoadingView()
    }
    private lazy var refreshView: RefreshView = RefreshView.refreshView()
    
    
}
